<!--
 * @Author: your name
 * @Date: 2021-03-15 20:53:56
 * @LastEditTime: 2021-03-15 20:56:17
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edi
 * @FilePath: \study\js\面试题\数组计算.html
-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>

    <body>
        <p><a href="https://blog.csdn.net/weixin_42412046/article/details/81459294">js数组去重的10种方法</a></p>
        <p>数组去重</p>
        <script>
            var list = [1, 1, 'true', 'true', true, true, 15, 15, false, false, undefined, null, null, NaN, NaN, 'NaN', 0, 0, 'a', 'a', {}, {}];

            console.warn(` \n1  [...new Set(list)]`);
            console.log([...new Set(list)]);

            console.warn(` \n1  Array.from(new Set(list)`);
            console.log(Array.from(new Set(list)));

            console.warn(` \n1  map`);
            let a = [];
            list.map((item, index, arr) => {
                if (!a.includes(item)) {
                    a.push(item);
                }
            });
            console.log(a);

            console.warn(` \n1  filter`);
            function unique(arr) {
                return arr.filter(function (item, index) {
                    // console.log(item, arr.indexOf(item, 0), index);
                    //当前元素，在原始数组中的第一个索引==当前索引值，否则返回当前元素
                    return arr.indexOf(item, 0) === index;
                });
            }
            console.log(unique(list));

            console.warn(` \n1  reduce`);
            function unique(arr) {
                return arr.reduce((prev, cur) => {
                    return prev.includes(cur) ? prev : [...prev, cur];
                }, []);
            }
            console.log(unique(list));
            // [1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}, {…}]


            const arr1 = [1, 2, 2, 3, 4, 4];
            const map = new Map();
            const uniqueArr = [];
            for(let item of arr1) {
            if(!map.has(item)) {
                map.set(item, true);
                uniqueArr.push(item);
            }
            }
            console.log(uniqueArr); // [1, 2, 3, 4]
        </script>
    </body>
</html>
